package android.textIt.frontend.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.textIt.backend.dao.UserDao;
import android.textIt.util.TextItUtil;
import android.util.Log;

public class TextItServiceReceiver extends BroadcastReceiver {
	private final static  String DEBUG_TAG = "TextIt c2dm";  

	private Context context;
	@Override
	public void onReceive(Context context, Intent intent) {
	    this.context = context;
		if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
	        handleRegistration(context, intent);
    } else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
	        handleMessage(context, intent);
    }
	}

	private void handleRegistration(Context context, Intent intent) {
    String registration = intent.getStringExtra("registration_id");
    if (intent.getStringExtra("error") != null) {
        // Registration failed, should try again later.
	    Log.d(DEBUG_TAG, "registration failed");
	    String error = intent.getStringExtra("error");
	    if(error == "SERVICE_NOT_AVAILABLE"){
	    	Log.d(DEBUG_TAG, "SERVICE_NOT_AVAILABLE");
	    }else if(error == "ACCOUNT_MISSING"){
	    	Log.d(DEBUG_TAG, "ACCOUNT_MISSING");
	    }else if(error == "AUTHENTICATION_FAILED"){
	    	Log.d(DEBUG_TAG, "AUTHENTICATION_FAILED");
	    }else if(error == "TOO_MANY_REGISTRATIONS"){
	    	Log.d(DEBUG_TAG, "TOO_MANY_REGISTRATIONS");
	    }else if(error == "INVALID_SENDER"){
	    	Log.d(DEBUG_TAG, "INVALID_SENDER");
	    }else if(error == "PHONE_REGISTRATION_ERROR"){
	    	Log.d(DEBUG_TAG, "PHONE_REGISTRATION_ERROR");
	    }
    } else if (intent.getStringExtra("unregistered") != null) {
        // unregistration done, new messages from the authorized sender will be rejected
    	Log.d(DEBUG_TAG, "unregistered");

    } else if (registration != null) {
  		Log.d(DEBUG_TAG, registration);
      // Send the registration ID to the 3rd party site that is sending the messages.
      // This should be done in a separate thread.
      // When done, remember that all registration is done.
  		UserDao userDAO = new UserDao(context);
  		userDAO.saveRegistrationId(registration);
	    return;
    }
}

		private void handleMessage(Context context, Intent intent)
		{
			//Do whatever you want with the message
		}	
}
